/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonSaveResultVo;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseAppendixRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.CaseDocumentAuthedEntrustDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAuthedEntrustMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentAuthedEntrust;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.ICaseDocumentAuthedEntrustService;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 描述: 授权委托书信息表 case_document_authed_entrust_doc 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月17日
 */
@Service
public class CaseDocumentAuthedEntrustServiceImpl extends MyBatisServiceSupport implements ICaseDocumentAuthedEntrustService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseDocumentAuthedEntrustServiceImpl.class);

    @Resource
    private CaseDocumentAuthedEntrustMapper caseDocumentAuthedEntrustMapper;

    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;

    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    CaseReasonMainRecordMapper caseReasonMainRecordMapper;

    @Resource
    IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    /***
     * 保存授权委托书
     * @author lxj
     * @date  2022/2/25
     * @param  caseDocumentAuthedEntrustDto 入参
     * @return boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public DocumentCommonSaveResultVo saveAuthEntrust(CaseDocumentAuthedEntrustDto caseDocumentAuthedEntrustDto) {
        DocumentCommonSaveResultVo resultVo=new DocumentCommonSaveResultVo();

        //判断当事人id
        if (ObjectUtils.isEmpty(caseDocumentAuthedEntrustDto.getPartyId())) {
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseDocumentAuthedEntrustDto.getCaseId());
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())) {
                throw new BusinessException("多当事人案件请指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseDocumentAuthedEntrustDto.getCaseId());
            String partyId = map.get("partyId");
            caseDocumentAuthedEntrustDto.setPartyId(partyId);
        }

        CaseDocumentAuthedEntrust caseDocumentAuthedEntrust = new CaseDocumentAuthedEntrust();
        BeanUtils.copyProperties(caseDocumentAuthedEntrustDto, caseDocumentAuthedEntrust);
        //校验姓名身份证是否正确
        boolean checkCert = commonService.checkRealNameDifferent(caseDocumentAuthedEntrustDto.getAuthedCertNo(),caseDocumentAuthedEntrustDto.getAuthedName());
        if(checkCert){
            throw new BusinessException("姓名身份证不匹配！");
        }
        //1.判定当前当事人是否存在一条授权委托数据，有则删除
        Example entrustExample = new Example(CaseDocumentAuthedEntrust.class);
        entrustExample.createCriteria().andEqualTo("caseId",caseDocumentAuthedEntrust.getCaseId()).andEqualTo("status",Constant.INTEGER_1)
                .andEqualTo("partyId", caseDocumentAuthedEntrust.getPartyId());//新增当事人id参数
        caseDocumentAuthedEntrustMapper.deleteByExample(entrustExample);
        //2.添加新的授权委托书
        caseDocumentAuthedEntrust.setCreateTime(LocalDateTime.now());
        caseDocumentAuthedEntrust.setId(BaseUtil.createUid());
        caseDocumentAuthedEntrust.setStatus(Constant.INTEGER_1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        caseDocumentAuthedEntrust.setAuthedTime(LocalDateTime.parse(caseDocumentAuthedEntrustDto.getAuthedTime()+":00",df));
        caseDocumentAuthedEntrustMapper.insert(caseDocumentAuthedEntrust);
        //3.调用文书生成公用方法-
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseDocumentAuthedEntrust.getCaseId());
        saveDto.setDocumentCatalogCode(caseDocumentAuthedEntrust.getDocumentCatalogCode());
        caseDocumentAuthedEntrustDto.setAuthedCreateDate(BaseUtil.getNowDate());
        caseDocumentAuthedEntrustDto.setAuthedTimeFormat(BaseUtil.getFormatDateTime(caseDocumentAuthedEntrustDto.getAuthedTime()));
        UserDTO userDTO = UserUtil.getUserInfo();
        caseDocumentAuthedEntrustDto.setOrgStandardName(commonService.getOrgStandardNameByOrgCode(userDTO.getOrgCode(),userDTO.getDeptCode()));
        saveDto.setDataMap(BaseUtil.javaToMap(caseDocumentAuthedEntrustDto));
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setPartyId(caseDocumentAuthedEntrustDto.getPartyId());
        Map<String,Object> resultMap = stageDocCommonOperateService.saveDocInfo(saveDto);
        String status= MapUtils.getString(resultMap,"success","");
        if(!"true".equals(status)){
            logger.info("----saveAuthEntrust接口调用saveDocInfo失败，返回："+resultMap);
            throw new NullPointerException();
        }
        resultVo.setDocumentId( MapUtils.getString(resultMap,"documentId", MapUtils.getString(resultMap,"documentId")));
        resultVo.setDocumentCatalogCode( MapUtils.getString(resultMap,"documentCatalogCode",MapUtils.getString(resultMap,"documentCatalogCode")));
        //4.判断是否有附件，没有就直接返回了
        if(StringUtils.isEmpty(caseDocumentAuthedEntrust.getAppendixUrl())){
            return resultVo;
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        //获取流程信息--调用公用接口
        RelationWorkflowInfoRequest request = new  RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        Example example = new Example(CaseReasonMainRecord.class);
        example.orderBy("createTime").desc();
        example.createCriteria().andEqualTo("caseId",caseDocumentAuthedEntrust.getCaseId()).andEqualTo("status",Constant.STRING_1);

        CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecordMapper.selectByExample(example).get(0);
        request.setApplyFieldCode(caseReasonMainRecord.getTerritoryCode());

        Map<String,Object> retMap = configBusiParamMainService.getRelationWorkflowInfo(request);
        if(retMap==null||retMap.get("success").toString().equals("false")){
            logger.info("----saveAuthEntrust接口调用getRelationWorkflowInfo失败，返回："+retMap);
            throw new NullPointerException();
        }
        String workFlowCode = retMap.get("WORKFLOWCODE").toString();
        //ConfigCaseFlowMainInfo configCaseFlowMainInfo = (ConfigCaseFlowMainInfo)retMap.get("WORKFLOWCODE");
        //4.附件
        CaseAppendixRecord appendixRecord = new CaseAppendixRecord();
        appendixRecord.setAppendixTypeId("1");
        appendixRecord.setAppendixUrl(caseDocumentAuthedEntrust.getAppendixUrl());
        appendixRecord.setAppendixName(caseDocumentAuthedEntrustDto.getAppendixName());
        appendixRecord.setCaseId(caseDocumentAuthedEntrust.getCaseId());
        //TODO 这里数据赋值不完整
        /*appendixRecord.setCaseLinkCode(configCaseFlowMainInfo.getCaseLinkCode());
        appendixRecord.setCaseLinkName(configCaseFlowMainInfo.getCaseLinkName());
        appendixRecord.setCaseStageCode(configCaseFlowMainInfo.getCaseStageCode());
        appendixRecord.setCaseStageName(configCaseFlowMainInfo.getCaseStageName());*/
        appendixRecord.setDocumentCatalogCode(caseDocumentAuthedEntrustDto.getDocumentCatalogCode());
        appendixRecord.setPartyId(caseDocumentAuthedEntrustDto.getPartyId());
        Example delExample = new Example(CaseAppendixRecord.class);
        delExample.createCriteria().andEqualTo("caseId",caseDocumentAuthedEntrustDto.getCaseId()).andEqualTo("documentCatalogCode",caseDocumentAuthedEntrustDto.getDocumentCatalogCode())
                .andEqualTo("partyId",caseDocumentAuthedEntrustDto.getPartyId());
        caseAppendixRecordMapper.deleteByExample(delExample);
        caseAppendixRecordService.saveCaseAppendixRecord(appendixRecord);
        return resultVo;
    }
}
